package com.tcat.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tcat.common.enums.ExceptionEnum;
import com.tcat.common.exception.TcatException;
import com.tcat.common.vo.PageResult;
import com.tcat.item.mapper.OrderMapper;
import com.tcat.item.mapper.StockMapper;
import com.tcat.item.pojo.Orders;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StockMapper stockMapper;

    public PageResult<Orders> queryOrderByPage(Integer page, Integer rows, String sortBy, Boolean desc, String search) {
        //分页
        PageHelper.startPage(page,rows);
        /*
           WHERE 'name' like '%x%' OR letter =='x'
           ORDER BY id DESC
         */
        //过滤
        Example example=new Example(Orders.class);
        if(StringUtils.isNotBlank(search)){
            example.orderBy("ordertime");
            example.createCriteria().orLike("consumerPhone","%"+search+"%");
                    //.orEqualTo("letter",search.toUpperCase());
        }
        //排序
        if(StringUtils.isNotBlank(sortBy)){
            String orderByClause=sortBy +(desc ? " DESC":" ASC");
            example.setOrderByClause(orderByClause);
        }
        //查询
        //分页助手会拦截查询并对他进行分页
        Page<Orders> list = (Page<Orders>)orderMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            throw new TcatException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        //解析分页结果
        PageInfo<Orders> info=new PageInfo<>(list);
        return new PageResult<>(info.getTotal(),list);
    }


    /**
     * 新增订单
     * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveOrders(Orders order) {

        order.setId(null);
        int count = orderMapper.insert(order);
        if(count!=1){
            throw new TcatException(ExceptionEnum.ORDER_SAVE_ERROR);
        }else{
            stockMapper.decreaseStock(order.getSkuId(),1);
        }
    }

    /**
     * 订单更新
     * @param order
     */
    @Transactional(rollbackFor=Exception.class)
    public void updateOrders(Orders order){
        this.orderMapper.updateByPrimaryKeySelective(order);
    }


    /**
     * 删除品牌  单个（多个删除则每个遍历每个品牌进行删除）
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrders(long id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    public int countOrders(){
        return orderMapper.selectAll().size();
    }

}
